package com.example.djetpack.lifecycle

import android.app.Activity
import android.app.Application
import android.os.Bundle
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import java.util.concurrent.ConcurrentHashMap

object AppLifecycleOwner : LifecycleOwner {

    private var mActivityStartCount = 0
    private val mLifecycleRegistry = LifecycleRegistry(this)

    private var mFront = true

    override fun getLifecycle(): Lifecycle {
        return mLifecycleRegistry
    }

    fun init(application: Application) {
        application.registerActivityLifecycleCallbacks(object : SimpleActivityLifecycleCallbacks() {
            override fun onActivityStarted(activity: Activity) {
                mActivityStartCount++
                //activity start的数量大于0 且 app是非前台
                if (mActivityStartCount > 0 && !mFront) {
                    mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
                    mFront = true
                }
            }

            override fun onActivityStopped(activity: Activity) {
                mActivityStartCount--
                if (mActivityStartCount <= 0 && mFront) {
                    mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
                    mFront = false
                }
            }
        })
    }

    abstract class AppLifecycleObserver : LifecycleEventObserver {
        override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
            if (event == Lifecycle.Event.ON_START) {
                onAppStateChange(true)
            } else if (event == Lifecycle.Event.ON_STOP) {
                onAppStateChange(false)
            }
        }

        abstract fun onAppStateChange(front: Boolean)

    }

    abstract class SimpleActivityLifecycleCallbacks : Application.ActivityLifecycleCallbacks {
        override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        }


        override fun onActivityResumed(activity: Activity) {
        }

        override fun onActivityPaused(activity: Activity) {
        }

        override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
        }

        override fun onActivityDestroyed(activity: Activity) {
        }
    }
}